package diva.pap;

import static diva.lib.lang.Lang.is;

import android.content.Context;
import diva.android_library.rpc.Response;
import diva.lib.net.UrlBuilder;
import diva.pap.model.RequestBase;

public class LoginRequest extends RequestBase<LoginRequest> {

  private String url;
  private String password;
  private String username;

  public LoginRequest(Context context, Response<LoginRequest> response) {
    super(context, "login", response);
  }

  public LoginRequest(Context context, String url, String username, String password,
      Response<LoginRequest> response) {
    super(context, "login", response);
    this.url = url;
    this.password = password;
    this.username = username;
  }

  public LoginRequest(Response<LoginRequest> response) {
    super(null, "login", response);
  }

  public String getSessionId() {
    return data.getString("session");
  }

  @Override
  public UrlBuilder getUrl() {
    if (is(url))
      return createLoginUrl(url, getAction(), username, password);
    else return createLoginUrl(application.getSettings().getServerUrl(), getAction(), application
        .getSettings().getUsername(), application.getSettings().getPassword());
  }

  public boolean isMerchant() {
    return "merchant".equals(data.getString("user_type"));
  }

  @Override
  public void run() {
    process();
  }

  @Override
  protected void onRequestSuccess(Response<LoginRequest> response) {
    if (isSuccess()) application.setSession(getSessionId());
    super.onRequestSuccess(response);
  }

}
